﻿//Constructor for task objects
var Task = function (
    //This is the title of the task
    name
    ) {
    this.name = name;
    this.isDone = false;
    this.startTime = Date.now();
}
//The arra to hold tasks
var tasks = [];
//Adds Tasks to Tasks Array
var addTask = function () {
    //Access Element
    var e = document.getElementById("taskName");
    //New Object
    //Extract Value
    var t = new Task(e.value);
    //Push to Array
    tasks.push(t);
    //Clear input
    e.value = "";
    //Write to table
    tableWriter();
};
//Write tasks to table
var tableWriter = function () {
    var h = "<table class='table table-striped table-hover'>";
    h += "<tr><th>Task</th></tr>";
    //for (var i = 0; i < tasks.length; i++)
    for (var i in tasks) {
        var time = "";
        if (tasks[i].isDone) {
            h += "<tr class='danger' >";
          time = "<td>" + (tasks[i].endTime - tasks[i].startTime)/1000 + "</td>";
        }
        else {
            h += "<tr  >";
        }
        h += "<td onclick='toggleDone(" + i + ")'>" + tasks[i].name + "</td>";
               // h += "<td>" + tasks[i].name + "</td>";
        h += "<td>" + new Date(tasks[i].startTime).toLocaleString() + "</td>";
        h += "<td><div class='btn btn-danger'onclick='deleteTask(" + i + ")'>Delete</div></td>";
        if (time) {
            h += time;
            
        }
        
 //h += "<input type='submit' value='Delete' class='btn btn-danger'onclick='deleteTask(" + i + ")'/>";
 

        h += "</tr>";
    }
    h += "</table>";
    document.getElementById("tableHolder").innerHTML = h;
};
//Marks tasks complete
var toggleDone = function (/*Index of element to mark*/index) {
    //Set object that the task is done
    tasks[index].isDone = !tasks[index].isDone;
    //set Finish Time
    tasks[index].endTime = Date.now();
    //Show user marked done(or not) aka write table
    tableWriter();

};
//Sort by done
var sortDone = function () { };
//Clear Finished
var clearDone = function () {
    for (var i = tasks.length - 1; i >= 0; i--) {
        if (tasks[i].isDone === true) {
            tasks.splice(i, 1);
        }
    }
    tableWriter();
};
//Delete single Task
var deleteTask = function (index) {
    tasks.splice(index, 1);
    tableWriter();
};
